<?php

class Router
{
	public $WWWFolder;
	
	// file extensions with their corresponding function
	public $ExtensionFn = array( 
		'/Start.phpx' => 'ExecPHPX', '/Start.php' => 'ExecPHP', '/Start.html' => 'ExecHTML', '/Start.htm' => 'ExecHTML',
		'/start.phpx' => 'ExecPHPX', '/start.php' => 'ExecPHP', '/start.html' => 'ExecHTML', '/start.htm' => 'ExecHTML',
		'.phpx' => 'ExecPHPX', '.php' => 'ExecPHP', '.html' => 'ExecHTML', '.htm' => 'ExecHTML' );
	
	public function __construct( $WWWFolder )
	{
		$this->WWWFolder = $WWWFolder;
	}
	
	public function Route( $Path = -1 )
	{
		// extract path from request uri if it is not given
		if($Path == -1)
		{
			$Path = $_SERVER['REQUEST_URI'];
			if(strpos($Path, '?') !== false)
				$Path = stristr($Path, '?', true);
		}
		
		// try if the path can be directly routed
		$Success = $this->TryRoute( $Path );
		
		while( !$Success && strlen( $Path ) > 0 )
		{
			// remove the portion after the last / and try again
			$Pos = strrpos( $Path, '/' );
			if( !$Pos )
			{
				$Path = '';
			}
			else
			{
				$Path = substr( $Path, 0, $Pos );
			}
			
			$Success = $this->TryRoute( $Path );				
		}
		
		// no start page found in the www folder
		if( !$Success )
			throw new Exception('Homepage not found');
	}
	
	// check for every recognized file type if it exists
	// if it exists, run it and return true, else return false
	public function TryRoute( $Path )
	{
		$FullPath = $this->WWWFolder . '/' . $Path;		
		foreach( $this->ExtensionFn as $Extension => $Fn )
		{
			$FilePath = $FullPath . $Extension;
			if( file_exists( $FilePath ) )
			{
				$this->$Fn( $FilePath );
				return true;
			}
		}
		return false;
	}

	// functions for handling different file types 
	
	public function ExecPHPX( $Path )
	{
		$XML = simplexml_load_file( $Path );
		$Page = PHPX::GenerateComponent( $XML );
		$Page->Render( );
	}
		
	public function ExecPHP( $Path )
	{
		require $Path;
	}
			
	public function ExecHTML( $Path )
	{
		readfile( $Path );
	}
}

?>